require File.join(File.dirname(__FILE__),'/geocode')

class CityCreator

  attr_writer :state

  def initialize(base='./')
    @base = base
    @state = nil
    
    # Ensure we have a trailing slash!
    if @base !~ /\/$/
      @base += '/'
    end
  end

  def create_from_args(argv)
    name = argv.shift
    
    title = nil
    if ARGV.empty?
      title = Util::un_camel_case name
      title = title.downcase
    else
      title = ARGV.shift
    end
    create name,title
  end

  def create(name,title)

    initials = name
    initials = initials.gsub /\s+/, ''
    initials = initials.gsub /[a-z]+/, ''
    initials = initials.downcase
    
    if !File.exists? name
      Dir.mkdir name
    end
    
    system "cat #{@base}../templates/city.php | sed -e 's/_initials_/#{initials}/g' | sed -e 's/_title_/#{title}/g' | sed -e 's/_base_/#{@base.gsub(/\//,'\/')}/g' > #{name}/index.php"
    system "cp #{@base}../templates/generate #{name}/generate"
    system "chmod +x #{name}/generate"
    system "cp #{@base}../templates/Makefile.city #{name}/Makefile"
    system "cp #{@base}../templates/coords.php #{name}/coords.php"
    
    geo = Geocode.new
    geo.verbose = false
    arr = geo.geocode name,@state
    if arr
      latitude,longitude = arr
      File.open("#{name}/coords.php", 'w') do |f|
        f.write "<?php\n"
        f.write "define('LONGITUDE_START'," + longitude.to_s + ");\n"
        f.write "define('LATITUDE_START'," + latitude.to_s + ");\n"
        f.write "?>"
      end
    end
    #system "#{@base}../geocode #{name} > #{name}/coords.php"
  end
end
